package com.example.demo1.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhangliuning
 */
@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {

        System.out.println("执行 ShiroFilterFactoryBean.shiroFilter()");

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //必须设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);


        //需要登录的接口，如果访问某个接口，需要登录却没登录，则调用此接口(如果不是前后端分离，则跳转页面)
        shiroFilterFactoryBean.setLoginUrl("/pub/need_login");

        //登录成功，跳转url，如果前后端分离，则没这个调用
        shiroFilterFactoryBean.setSuccessUrl("/");

        //没有权限，未授权就会调用此方法， 先验证登录-》再验证是否有权限
        shiroFilterFactoryBean.setUnauthorizedUrl("/pub/not_permit");


        //拦截器路径，坑一，部分路径无法进行拦截，时有时无；是因为使用的是hashmap, 无序的，应该改为LinkedHashMap
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();


//        设置自定义Filter
        Map<String, Filter> filtersMap = new LinkedHashMap<>();
        filtersMap.put("roleOrFilter", new CustomRolesOrAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filtersMap);


        /*
         * logout、annon、authc、perms，这几个都是Shiro的内置过滤器
         *   自定义过滤器及其别名定义在类 DefaultFilter 中
         * roleOrFilter是自定义过滤器
         * */

        //退出过滤器，这个不配置也行，默认访问 logout，shiro就会清空对应的token
//        当前接口访问后，对应的token相当于失效了
        filterChainDefinitionMap.put("/logout", "logout");

        //匿名可以访问，也是就游客模式，一般用于过滤静态资源
        filterChainDefinitionMap.put("/pub/**", "anon");

        //登录用户才可以访问
        filterChainDefinitionMap.put("/authc/**", "authc");

        //管理员角色才可以访问
//        filterChainDefinitionMap.put("/admin/**", "roles[admin,root]");即当前用户同时拥有admin和root角色
//        具有admin或root角色就可以访问
        filterChainDefinitionMap.put("/admin/**", "roleOrFilter[admin,root]");


        //有编辑权限才可以访问，与roles类似，也可以配置为perms[perm1,perm2]，表示多个权限需要同时满足
        filterChainDefinitionMap.put("/video/update", "perms[video_update]");

        /*
        哪些url需要哪些角色才能访问，这部分还是配置到数据库中，然后这里再根据配置进行初始化
         */


        //坑二: 过滤链是顺序执行，从上而下，一般将/** 放到最下面

        //authc : url定义必须通过认证才可以访问
        //anon  : url可以匿名访问
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }


    @Bean
    public SecurityManager securityManager() {

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

//        如果不是前后端分离的项目，则没必要设置 sessionManager
        securityManager.setSessionManager(sessionManager());
        //使用自定义的cacheManager
        securityManager.setCacheManager(cacheManager());
//        最后再设置realm
        securityManager.setRealm(customRealm());


        return securityManager;
    }


    /**
     * 自定义Realm
     *
     * @return
     */
    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm = new CustomRealm();
//        这里为了方便不设置散列作为密码的加密算法，如果需要的话，再打开即可
//        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        /*
        如果需要加密，则先对密码做加密处理
        String hashName = "md5";
        String pwd = "123456";
        SimpleHash simpleHash = new SimpleHash(hashName, pwd, null, 2);
        System.out.println(simpleHash);
         */
        return customRealm;
    }


    /**
     * 配置密码加解密规则
     *
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();

        //设置散列算法：这里使用的MD5算法
        credentialsMatcher.setHashAlgorithmName("md5");
        //散列次数，好比散列2次，相当于md5(md5(xxxx))
        credentialsMatcher.setHashIterations(2);

        return credentialsMatcher;
    }


    @Bean
    public SessionManager sessionManager() {
        /*
        DefaultSessionManager： 默认实现，常用于javase
        ServletContainerSessionManager: web环境
        DefaultWebSessionManager：常用于自定义实现
         */
        CustomSessionManager customSessionManager = new CustomSessionManager();
        //配置session持久化
        customSessionManager.setSessionDAO(redisSessionDAO());
//        设置sessionId超时时间,单位：毫秒
        customSessionManager.setGlobalSessionTimeout(1000 * 3000);

        return customSessionManager;
    }

    /**
     * 配置redisManager
     */
    public RedisManager getRedisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost("localhost:6379");
        return redisManager;
    }


    /**
     * 配置具体cache实现类
     *
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(getRedisManager());
        //设置过期时间，单位是秒，20s,
        redisCacheManager.setExpire(20);

        return redisCacheManager;
    }

    /**
     * 自定义session持久化
     *
     * @return
     */
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(getRedisManager());
        //设置sessionid生成器，最好自己实现，只需要实现 SessionIdGenerator 接口即可
//        redisSessionDAO.setSessionIdGenerator(new CustomSessionIdGenerator());
        return redisSessionDAO;
    }

//    下面为Shiro常用Bean

    /**
     * 管理Shiro Bean的生命周期
     *
     * @return
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        LifecycleBeanPostProcessor lifecycleBeanPostProcessor = new LifecycleBeanPostProcessor();
        return lifecycleBeanPostProcessor;
    }

    /**
     * 配置了这个Bean，Shiro的注解配置，如 @RequiresRoles、@RequiresPermissions、@RequiresAuthentication、@RequiresUser 才能使用
     * 如果还是无效，应该是AOP没有起到作用，解决办法见：https://www.cnblogs.com/tuifeideyouran/p/7696055.html
     *
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 扫描所有的Advisor
     * 创建了LifecycleBeanPostProcessor后才能创建DefaultAdvisorAutoProxyCreator
     * @return
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

}
